from apps.user.dao import UserDao
from apps.system.team.dao import TeamDao
from apps.pay.recordIncomes.dao import RecordIncomesDao
from decimal import Decimal
def countTeamAwardFun(order, sendContributionValues):
    print('发放团队奖励')
    _user = UserDao().findOneByObjId(order.user.id)
    _teams = TeamDao().findAll().order_by('grade')
    lastTeam = _teams.first()
    if _user.parent:
        _parent = UserDao().findOneByObjId(_user.parent.id)
        while 1:
            if _parent:
                _parentTeam = _parent.team
                print('计算用户', _parent.id, _parentTeam.grade)
                if not _parentTeam:
                    _parent = _parent.parent
                    continue
                if _parentTeam.grade == 0:
                    _parent = _parent.parent
                    continue
                
                for team in _teams:
                    if _parentTeam.grade == team.grade and team.grade > lastTeam.grade:
                        print('满足条件计算奖励', _parent.id, team.grade)

                        award = round(sendContributionValues * team.awardRate)
                        addAward('teamAward', _parent, award, order)
                        # 计算平级奖励
                        # countLevelAward(_parent, award, order, team)
                        if _parent.parent:
                            levelAwardTarget = findLastRankByUserAndGrade(_parent.parent, team.grade)
                            if levelAwardTarget:
                                levelAward = round(award * 0.1)
                                addAward('levelAward', levelAwardTarget, levelAward, order)
                        lastTeam = team
                        break
                _parent = _parent.parent
                print('_parent', _parent)
            else:
                print('上级不存在')
                break
    else:
        print('上级不存在')

# 增加贡献值
def addAward(scene, _parent, award, order):
    print('发放团队贡献值', award)
    UserDao().addWallet('contributionValue', _parent, award)
    # 新增钱包记录
    data = {}
    data['scene'] =  scene
    data['user'] = _parent.id
    data['fromUser'] = order.user.id
    data['orderId'] = order.orderId
    data['money'] = Decimal(award)
    data['payway'] = 'contributionValue'
    data['changeWay'] = 'add'
    RecordIncomesDao().create(data)

# 查找最近级别的用户
def findLastRankByUserAndGrade(parent, grade):
    print('要查找的用户', parent)
    if parent.id:
        if parent.team.grade == grade:
            print('找到用户', parent)
            return parent
        else:
            print('不是级别为2的用户', parent)
            if parent.parent:
                return findLastRankByUserAndGrade(parent.parent, grade)
            return None
    else:
        print('一个级别为2的用户也没有')
        return None